<script setup>
	import { defineEmits, defineProps, reactive, computed, watch, ref, onMounted, onBeforeUnmount } from 'vue'
	import config from './config'
	import { cloneDeep } from 'lodash-es'
	import tool from '@/utils/tool'

	const emits = defineEmits(['upDataConfig'])

	const props = defineProps({
		config: {
			type: Object,
			default: () => cloneDeep(config)
		}
	})

	// 本地配置缓存，避免直接修改props
	const localConfig = reactive(cloneDeep(props.config))

	// 样式计算
	const container = computed(() => ({
		padding: `${localConfig.style.paddingT}px ${localConfig.style.paddingR}px ${localConfig.style.paddingB}px ${localConfig.style.paddingL}px`,
		background: localConfig.style.bgColor,
		borderColor: localConfig.style.borderColor,
		borderWidth: localConfig.style.borderWidth + 'px',
		borderStyle: localConfig.style.borderStyle,
		borderTopLeftRadius: localConfig.style.bgRTL + 'px',
		borderTopRightRadius: localConfig.style.bgRTR + 'px',
		borderBottomLeftRadius: localConfig.style.bgRBL + 'px',
		borderBottomRightRadius: localConfig.style.bgRBR + 'px',
		boxShadow: `${localConfig.style.shadowX}px ${localConfig.style.shadowY}px ${localConfig.style.shadowDegree}px ${localConfig.style.shadowColor}`
	}))

	const titleStyle = computed(() => ({
		fontSize: localConfig.style.titleSize + 'px',
		color: localConfig.style.titleColor,
		fontWeight: localConfig.style.titleWeight ? 800 : 500,
		fontStyle: localConfig.style.titleStyle ? 'italic' : '',
		textDecoration: localConfig.style.titleLine ? 'underline' : ''
	}))

	const contentStyle = computed(() => ({
		fontSize: localConfig.style.roleSize + 'px',
		color: localConfig.style.roleColor,
		fontWeight: localConfig.style.roleWeight ? 800 : 500,
		fontStyle: localConfig.style.roleStyle ? 'italic' : '',
		textDecoration: localConfig.style.roleLine ? 'underline' : '',
		marginTop: '20px'
	}))

	const timeStyle = computed(() => ({
		fontSize: localConfig.style.timeSize + 'px',
		color: localConfig.style.timeColor,
		fontWeight: localConfig.style.timeWeight ? 800 : 500,
		fontStyle: localConfig.style.timeStyle ? 'italic' : '',
		textDecoration: localConfig.style.timeLine ? 'underline' : ''
	}))

	const avatarStyle = computed(() => ({
		display: localConfig.style.avatarShow ? 'flex' : 'none',
		width: localConfig.style.avatarSize + 'px',
		height: localConfig.style.avatarSize + 'px',
		borderRadius: localConfig.style.avatarShape === 'circle' ? '50%' : '4px'
	}))

	const iconBoxStyle = computed(() => ({
		display: props.config.style.iconShow ? 'flex' : 'none',
		backgroundColor: props.config.style.iconBgColor,
		height: props.config.style.iconBgSize + 'px',
		width: props.config.style.iconBgSize + 'px',
		borderTopLeftRadius: props.config.style.iconRTL + 'px',
		borderTopRightRadius: props.config.style.iconRTR + 'px',
		borderBottomLeftRadius: props.config.style.iconRBL + 'px',
		borderBottomRightRadius: props.config.style.iconRBR + 'px'
	}))
	const iconStyle = computed(() => ({
		color: props.config.style.iconColor,
		fontSize: props.config.style.iconSize + 'px'
	}))

	// 监听props变化，更新本地配置
	watch(
		() => props.config,
		(newConfig) => {
			Object.assign(localConfig, cloneDeep(newConfig))
		},
		{ deep: true }
	)

	// 初始化数据
	const dataSet = reactive(cloneDeep(config.data))

	// 动态时间
	const currentTime = ref('')
	let timer = null

	// 格式化时间函数
	const formatTime = () => {
		const now = new Date()
		const year = now.getFullYear()
		const month = String(now.getMonth() + 1).padStart(2, '0')
		const day = String(now.getDate()).padStart(2, '0')
		const hours = String(now.getHours()).padStart(2, '0')
		const minutes = String(now.getMinutes()).padStart(2, '0')
		const seconds = String(now.getSeconds()).padStart(2, '0')
		return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`
	}

	// 更新时间
	const updateTime = () => {
		currentTime.value = formatTime()
	}

	// 组件挂载时启动定时器
	onMounted(() => {
		updateTime() // 立即更新一次
		timer = setInterval(updateTime, 1000) // 每秒更新一次
	})

	// 组件卸载前清除定时器
	onBeforeUnmount(() => {
		if (timer) {
			clearInterval(timer)
			timer = null
		}
	})

	// 从localStorage获取用户信息并更新数据集
	const getUserInfoFromCache = () => {
		try {
			const userInfo = tool.data.get('USER_INFO')
			if (userInfo && typeof userInfo === 'object') {
				// 根据配置的字段映射获取对应的值
				const nameField = localConfig.data.name.field || 'name'
				const roleField = localConfig.data.role.field || 'orgName'
				const avatarField = localConfig.data.avatar.field || 'avatar'

				// 更新数据集
				dataSet.name.value = userInfo[nameField] || userInfo.name || 'superAdmin'

				// 角色字段处理：如果是orgName，则组合显示
				if (roleField === 'orgName') {
					dataSet.role.value = userInfo.orgName ? `${userInfo.orgName} | ${userInfo.positionName || ''}` : '测试 | 超管'
				} else {
					dataSet.role.value = userInfo[roleField] || '测试 | 超管'
				}

				dataSet.avatar.value = userInfo[avatarField] || userInfo.avatar || ''
			} else {
				// fallback 默认值
				dataSet.name.value = 'superAdmin'
				dataSet.role.value = '测试 | 超管'
				dataSet.avatar.value = ''
			}
		} catch (error) {
			console.error('Error getting user info from cache:', error)
			// 出错时使用默认值
			dataSet.name.value = 'superAdmin'
			dataSet.role.value = '测试 | 超管'
			dataSet.avatar.value = ''
		}
	}

	// 初始化时获取用户信息
	getUserInfoFromCache()

	// 组件绑定数据，统一使用缓存数据
	const formState = computed(() => {
		return dataSet
	})

	// 更新配置
	const updateConfig = (newConfig) => {
		console.log('更新配置', newConfig)
		Object.assign(localConfig, newConfig)
		// 当配置更新时，重新获取用户信息以应用新的字段映射
		getUserInfoFromCache()
		emits('upDataConfig', cloneDeep(localConfig))
	}

	// 监听配置变化，实时更新数据
	watch(
		() => [localConfig.data.name.field, localConfig.data.role.field, localConfig.data.avatar.field],
		() => {
			getUserInfoFromCache()
		},
		{ deep: true }
	)

	// 刷新数据方法
	const onReload = () => {
		// 重新获取用户信息
		getUserInfoFromCache()
		// 更新当前时间
		updateTime()
	}

	// 头像加载错误处理
	const handleImageError = (event) => {
		console.warn('Avatar image failed to load:', event.target.src)
		// 头像加载失败时，清空头像值，这样会显示占位符或图标
		dataSet.avatar.value = ''
	}

	defineExpose({ onReload, updateConfig })
</script>

<template>
	<div class="user-info-card" :style="{ ...container }">
		<div class="user-info-layout">
			<!-- 左侧头像区域 -->
			<div class="user-avatar-section" v-if="localConfig.style.avatarShow">
				<div class="avatar-container" :style="{ ...iconBoxStyle }">
					<!-- 优先显示用户头像，如果没有则显示图标 -->
					<img
						:src="formState.avatar.value"
						:style="{ ...avatarStyle }"
						v-if="formState.avatar.value"
						@error="handleImageError"
					/>
					<div class="avatar-placeholder" :style="{ ...avatarStyle }" v-else-if="!localConfig.style.iconShow">
						{{ formState.name.value ? formState.name.value.substring(0, 1).toUpperCase() : 'S' }}
					</div>
					<i :class="['iconfont', localConfig.style.icon]" :style="{ ...iconStyle }" v-else></i>
				</div>
			</div>
			<!-- 右侧信息区域 -->
			<div class="user-info-section">
				<div class="user-name" :style="{ ...titleStyle }">{{ formState.name.value }}</div>
				<div class="user-role" v-if="localConfig.style.roleShow" :style="{ ...contentStyle }">
					{{ formState.role.value }}
				</div>
			</div>

			<!-- 当前时间 -->
			<div class="current-time" :style="{ ...timeStyle }" v-if="localConfig.style.timeShow">
				{{ currentTime }}
			</div>
		</div>
	</div>
</template>

<style scoped lang="less">
	.user-info-card {
		height: 100%;
		display: flex;
		overflow: auto;
	}

	.user-info-layout {
		display: flex;
		width: 100%;
		height: 100%;
		align-items: center;
	}

	.user-avatar-section {
		flex-shrink: 0;
		padding-right: 16px;
	}

	.user-info-section {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.avatar-container {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		display: inline-block;
	}

	.avatar-placeholder {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #3b8cff;
		color: #ffffff;
		font-size: 24px;
		font-weight: bold;
	}

	.user-name {
		width: 100%;
		word-break: break-word;
		margin-bottom: 4px;
		font-weight: 500;
	}

	.user-role {
		color: #999;
		font-size: 12px;
	}

	.current-time {
		font-size: 12px;
		color: #999;
	}
</style>
